<template>
  <div>
    <div
      v-for="(index, item) in total"
      :key="item"
      :style="{ background: getColor(item) }"
      class="grid-item"
      @click="changeIndex(item)"
    >
      <span>{{ item + 1 }}</span>
    </div>
    <div :key="item.id" class="head_item">
      {{ index + 1 }}.{{ item.question }}
    </div>
    <div class="context_item">
      <!-- 单选框 -->
      <van-radio-group v-model="selectedRatio" v-show="item.answer.length == 1">
        <div class="selectd_item">
          <van-radio name="A" @click="radioHandler">{{ item.item1 }}</van-radio>
        </div>
        <div class="selectd_item">
          <van-radio name="B" @click="radioHandler">{{ item.item2 }}</van-radio>
        </div>
        <div class="selectd_item">
          <van-radio name="C" @click="radioHandler">{{ item.item3 }}</van-radio>
        </div>
        <div class="selectd_item">
          <van-radio name="D" @click="radioHandler">{{ item.item4 }}</van-radio>
        </div>
      </van-radio-group>
      <!-- 多选框 -->
      <van-checkbox-group
        v-model="selectedChecked"
        v-show="item.answer.length > 1"
      >
        <div class="selectd_item">
          <van-checkbox name="A" @click="checkHandler" shape="square">{{
            item.item1
          }}</van-checkbox>
        </div>
        <div class="selectd_item">
          <van-checkbox name="B" @click="checkHandler" shape="square">{{
            item.item2
          }}</van-checkbox>
        </div>
        <div class="selectd_item">
          <van-checkbox name="C" @click="checkHandler" shape="square">{{
            item.item3
          }}</van-checkbox>
        </div>
        <div class="selectd_item">
          <van-checkbox name="D" @click="checkHandler" shape="square">{{
            item.item4
          }}</van-checkbox>
        </div>
      </van-checkbox-group>
    </div>
    <div class="remark_item" v-show="item.remark">
      答案解析：
      {{ item.remark }}
    </div>
    <div v-if="feedback" class="feed_item">
      <el-button style="margin-right: 20px" type="warning" @click="feedBack"
        >反馈错题</el-button
      >
    </div>
    <div class="func_item">
      <!-- 功能区，有提交，收藏，下一题，上一题等各种按钮 -->
      <div class="func_item_left">
        <div class="func_item_button">
          <van-button type="info" size="small" @click="showAnswer" icon="eye-o"
            >答案</van-button
          >
        </div>
        <div class="func_item_button">
          <van-button
            :type="tappedfalg ? 'warning' : 'info'"
            :icon="tappedfalg ? 'checked' : 'info'"
            size="small"
            @click="tap"
            >标 记</van-button
          >
        </div>
      </div>
      <div class="picker_box"></div>
      <div class="func_item_right">
        <div class="func_item_button">
          <van-button type="info" icon="arrow-left" size="small" @click="prev"
            >上一题</van-button
          >
        </div>
        <div class="func_item_button">
          <van-button type="info" icon="arrow" size="small" @click="next"
            >下一题</van-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import zhiZhaoApi from "@/api/questionItem/questionItem";
import feedBackApi from "@/api/feedBack";
import store from "@/store";
export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
      show: false,
      index: 0,
      total: 0,
      items: [], //所有的题
      item: {
        subject: "",
        question: "",
        item1: "",
        item2: "",
        item3: "",
        item4: "",
        answer: "",
      }, //单独的某一道题
      selectedRatio: "", //选择单选题的答案
      selectedChecked: [], //选择多选题的答案
      allAnswers: [], //选择的所有题目的答案
      tapIndex: [], //标记的题目的索引
      tappedfalg: false, //表示某一题是否被标记过的索引
      feedback: false,
    };
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {
    /**
     * 当页面发生改变时
     * 1.检测该页面的索引是否在tapIndex中
     * 2.重新渲染新的页面，生成新的题目
     * 3.以前做过的题目选项要回显
     * @param {index索引} newVal
     */
    index(newVal) {
      this.selectedRatio = "";
      this.selectedChecked = [];
      this.item = this.items[newVal];
      if (this.tapIndex.includes(newVal)) {
        this.tappedfalg = true;
      } else {
        this.tappedfalg = false;
      }
      const res = this.allAnswers[newVal].filter((a) => a != "");
      if (this.items[newVal].answer.length > 1) {
        //多选题
        this.selectedChecked = res;
      } else {
        //单选题
        this.selectedRatio = res[0];
      }
    },
  },
  //方法集合
  methods: {
    /**
     * 比较[ "A", "B", "C" ]和A+B+C这样一个数组和字符串是否相等
     * @param {数组} array
     * @param {字符串} str
     */
    compare(array, str) {
      if (array.length == 1) {
        // console.log("单选题的比较", array, str);
        return array[0] == str;
      } else {
        let arr = "";
        for (let index = 0; index < array.length; index++) {
          const element = array[index];
          arr += element;
          if (index < array.length - 1) {
            arr += "+";
          }
        }
        return arr == str;
      }
    },
    changeIndex(item) {
      this.index = item;
    },
    getColor(item) {
      //当页面刚渲染时，此时还未获取数据，而该方法已经在执行，此时会报undefined错误，为了避免这个错误，加了一个判断
      if (this.allAnswers[item] != undefined) {
        // console.log(this.allAnswers[item], this.items[item].answer);
        const answer = this.allAnswers[item].filter((a) => a != "");
        if (item == this.index) {
          //点击的题目的颜色
          return "#FF33FF";
          //标记的题目的颜色
        } else if (this.tapIndex.includes(item)) {
          return "#CCFF66";
        } else {
          //除了点击和标记的题目，就要看选择正确与否离开
          if (this.compare(answer, this.items[item].answer)) {
            //如果正确答案与选择答案比较相等，表示选对了
            return "#66CC99";
          } else {
            //否则说明选错了
            return "#993333";
          }
        }
      }
    },
    setAllAnswers(item) {
      switch (item) {
        case "A":
          this.allAnswers[this.index][0] = item;
          break;
        case "B":
          this.allAnswers[this.index][1] = item;
          break;
        case "C":
          this.allAnswers[this.index][2] = item;
          break;
        case "D":
          this.allAnswers[this.index][3] = item;
          break;
        default:
          // do something
          break;
      }
    },
    radioHandler() {
      for (let index = 0; index < 4; index++) {
        this.allAnswers[this.index][index] = "";
      }
      this.setAllAnswers(this.selectedRatio);
    },
    checkHandler() {
      for (let index = 0; index < 4; index++) {
        this.allAnswers[this.index][index] = "";
      }
      for (let index = 0; index < this.selectedChecked.length; index++) {
        const element = this.selectedChecked[index];
        this.setAllAnswers(element);
      }
    },
    /**
     * 标记该题目的索引
     */
    tap() {
      if (!this.tappedfalg) {
        this.tapIndex.push(this.index);
        this.tappedfalg = true;
      } else {
        this.tapIndex = this.tapIndex.filter((e) => e !== this.index);
        this.tappedfalg = false;
      }
    },
    next() {
      if (this.index == this.total - 1) {
        this.$message({
          message: "已经是最后一题了！",
          type: "error",
        });
        return;
      }
      this.index = this.index + 1;
    },
    prev() {
      if (this.index == 0) {
        this.$message({
          message: "已经是第一题了！",
          type: "error",
        });
        return;
      }
      this.index = this.index - 1;
    },
    //显示正确答案
    showAnswer() {
      if (this.item.answer.length == 1) {
        this.selectedRatio = this.item.answer;
      } else {
        let arr = this.item.answer.split("+");
        this.selectedChecked = arr;
      }
    },
    /**
     * 反馈错题
     */
    feedBack() {
      feedBackApi.insert(this.item.id).then((res) => {
        this.$message({
          message: `${res.message}`,
          type: "success",
        });
      });
    },
    /**
     * 当获取到考卷后，初始化一些数据
     * 1.初始化选择答案的数组
     * 2.从路劲中获取参数，再从数据库中获取考题
     */
    init() {
      const questionItemId = this.$route.query.questionItemId;
      const account = this.$route.query.account;
      if (!questionItemId || !account) {
        this.$router.push({ path: "/testResult/index" });
        return;
      }
      zhiZhaoApi.getItem(questionItemId).then((res) => {
        this.items = res.data.result;
        this.item = this.items[0];
        this.total = this.items.length;
        zhiZhaoApi.getMyAnswers(questionItemId, account).then((response) => {
          for (let index = 0; index < this.total; index++) {
            let arr = new Array();
            arr.push(response.data[index][0]);
            arr.push(response.data[index][1]);
            arr.push(response.data[index][2]);
            arr.push(response.data[index][3]);
            this.allAnswers.push(arr);
          }
          let ans = this.allAnswers[0].filter((a) => a != "");
          if (ans.length == 1) {
            this.selectedRatio = ans[0];
          } else {
            for (let index = 0; index < ans.length; index++) {
              const element = ans[index];
              this.selectedChecked.push(element);
            }
          }
        });
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.init();
    if (
      store.getters.roles.includes("teacher") ||
      store.getters.roles.includes("admin")
    ) {
      this.feedback = true;
    } else {
      this.feedback = false;
    }
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style scoped>
.grid-item {
  width: 40px;
  height: 40px;
  display: inline-block;
  margin: 2px;
  text-align: center;
  cursor: pointer;
}
.grid-item span {
  color: white;
}
.selectd_item {
  margin-top: 20px;
}

.head_item {
  margin-top: 20px;
}
.context_item {
  margin-top: 20px;
}
.feed_item {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.remark_item {
  margin-top: 20px;
}
.func_item {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.func_item_button {
  margin-left: 1px;
  margin-right: 1px;
}
.func_item_left {
  width: 29%;
  display: flex;
  justify-content: left;
}

.func_item_right {
  width: 39%;
  display: flex;
  justify-content: right;
}

.picker_box {
  background-color: white;
  width: 30%;
  margin-right: 2px;
  margin-left: 2px;
}
</style>